
package com.segment.dcore.servlet.filter;

import com.segment.dcore.base.constants.FilterOrderConstants;
import com.segment.dcore.base.filter.InvokeContext;
import com.segment.dcore.servlet.AbstractServletServiceFilter;
import com.segment.dcore.servlet.filter.context.ServletInvokeContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.IOException;

/**
 * servlet拦截器
 *
 * Created by huapeng.hhp on 2017/2/27.
 */
@Service("servletServiceInvokeFilter")
public class ServletServiceInvokeFilter extends AbstractServletServiceFilter {
	/** LOGGER for ServiceInvokeFilter */
	private static final Logger LOGGER = LoggerFactory.getLogger(ServletServiceInvokeFilter.class);

	public int getOrder() {
		return FilterOrderConstants.SERVICE_INVOKE_FILTER_ORDER;
	}

	@Override
	protected void before(InvokeContext invokeContext) {
		invokeContext.setStartTime(System.currentTimeMillis());
		ServletInvokeContext realInvokeContext = (ServletInvokeContext) invokeContext;
		ServletRequest request = realInvokeContext.getRequest();
		ServletResponse response = realInvokeContext.getResponse();
		FilterChain chain = realInvokeContext.getChain();
		try {
			chain.doFilter(request, response);
		} catch (IOException | ServletException e) {
			LOGGER.error("do ServletServiceInvoke error", e);
			throw new RuntimeException("do ServletServiceInvoke error", e);
		}
	}

	@Override
	protected void after(InvokeContext invokeContext) {
		invokeContext.setEndTime(System.currentTimeMillis());
	}
}
